<?php
class OCHeader {
	private $http_header=array();
	private $html_head=array();
	private static $storage=array();
	
	//stores object inside class
	public function storeInstance($id='main') {
		if(!empty($id)) {
			$storage[$id]=$this;
			return true;
		} else return false;
	}
	
	//get object from class
	public static function getInstance($id='main') {
		if(isset(self::$storage[$id])) return self::$storage[$id];
		else return false;
	}
	
	//Accept only relevant General or Server side headers. Will be sent only after page is generated.
	//When location header set, will esecute immideately
	public function addHeader($index,$value) {
		$this->http_header[$index]="$value";
		if(strtolower($index)=='location') $this->sentHeader();
		die('Redirect to page click <a href="'.$value.'">here</a>');
	}
	
	//Add's strings to <head>. Strings will be sorted by relevance, non relevant tags will be excluded
	public function addData($str) {
		$allowed_tags = array('base'=>0, 'link'=>2, 'meta'=>1, 'script'=>5, 'style'=>4, 'title'=>3);
		preg_match("/^\<([A-z]*)/i",$str,$match);
		if(isset($allowed_tags[strtolower($match[1])])) {
			$this->html_head[$allowed_tags[strtolower($match[1])]][]=$str;
			return true;
		} else return false;
	}
	
	//Returns http header data
	public function sentHeader() {
		$header = $this->http_header;
		$result='';
		foreach($header as $index=>$value) $result .= "$index:$value\r\n";
		header($result);
	}

	//Returns data to be inserted into <head> tag. if dublicate set, will also print HTTP headers wia <meta>
	public function printHead($dublicate=false) {
		$headers=$this->html_head;
		if($dublicate) 
		foreach($this->http_header as $index=>$value) $headers[1][]='<meta http-equiv="'.$index.'" content="'.$value.'" />';
		ksort($headers);
		$result='';
		foreach($headers as $value) foreach($value as $header) $result .= $header."\r\n";
		return $result;
	}
}
?>
